<template>
  <view class="search-page">
    <!-- 搜索栏 -->
    <view class="search-header">
      <view class="search-input-wrapper">
        <view class="icon icon-search" style="font-size: 20px; color: #999;">🔍</view>
        <input 
          v-model="searchKeyword" 
          type="text" 
          placeholder="搜索壁纸、标签" 
          class="search-input"
          @focus="showHistory = true"
          @confirm="handleSearch"
          :focus="autoFocus"
        />
        <view 
          v-if="searchKeyword" 
          class="icon icon-clear" 
          style="font-size: 20px; color: #999;" 
          @click="clearSearch"
        >✕</view>
      </view>
        <text class="cancel-btn" @click="handleCancel">取消</text>
    </view>
    
    <!-- 搜索历史 -->
    <view class="search-history" v-if="showHistory && !isSearching">
      <view class="history-header">
        <text class="history-title">搜索历史</text>
        <view class="icon icon-trash" style="font-size: 18px; color: #999;" @click="clearHistory">🗑️</view>
      </view>
      <view class="history-tags">
        <view 
          v-for="(item, index) in searchHistory" 
          :key="index"
          class="history-tag"
          @click="searchByHistory(item)"
        >
          {{ item }}
        </view>
      </view>
      <view class="hot-search" v-if="hotKeywords.length > 0">
        <text class="hot-title">热门搜索</text>
        <view class="hot-tags">
          <view 
            v-for="(item, index) in hotKeywords" 
            :key="index"
            class="hot-tag"
            :class="{ 'top-three': index < 3 }"
            @click="searchByKeyword(item)"
          >
            <text class="hot-rank" v-if="index < 3">{{ index + 1 }}</text>
            <text class="hot-keyword">{{ item }}</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 搜索结果 -->
    <view class="search-result" v-if="isSearching || wallpapers.length > 0">
      <view class="result-header" v-if="wallpapers.length > 0">
        <text>找到 {{ totalCount }} 个相关壁纸</text>
      </view>
      
      <!-- 壁纸列表 -->
      <wallpaper-grid 
        :wallpaper-list="wallpapers" 
        :has-more="hasMore" 
        :load-status="loadStatus"
        @wallpaper-click="navigateToDetail"
        @load-more="loadMoreWallpapers"
        @favorite="handleFavorite"
      />
      
      <!-- 无结果 -->
      <view class="no-result" v-if="isSearching && wallpapers.length === 0 && loadStatus !== 'loading'">
        <uni-icons type="search" size="64" color="#ccc" />
        <text class="no-result-text">没有找到相关壁纸</text>
        <text class="no-result-hint">换个关键词试试吧</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import {onLoad, onShow, watch } from "@dcloudio/uni-app"
import WallpaperGrid from '../../components/wallpaper-grid.vue';

// 状态管理
const searchKeyword = ref('');
const wallpapers = ref([]);
const searchHistory = ref([]);
const hotKeywords = ref(['自然风光', '动漫壁纸', '文字壁纸', '城市夜景', '艺术抽象', '汽车壁纸']);
const showHistory = ref(true);
const isSearching = ref(false);
const totalCount = ref(0);
const page = ref(1);
const size = ref(20);
const hasMore = ref(true);
const loadStatus = ref('more');
const autoFocus = ref(true);

// 模拟数据
const mockSearchResults = [
  {
    _id: 'search1',
    title: '搜索结果壁纸1',
    thumbnail_url: 'https://img-cdn-qiniu.dcloud.net.cn/uniapp/images/shuijiao.jpg',
    file_url: 'https://img-cdn-qiniu.dcloud.net.cn/uniapp/images/shuijiao.jpg',
    favorite_count: 128,
    download_count: 512,
    is_favorite: false
  },
  {
    _id: 'search2',
    title: '搜索结果壁纸2',
    thumbnail_url: 'https://img-cdn-qiniu.dcloud.net.cn/uniapp/images/banana.jpg',
    file_url: 'https://img-cdn-qiniu.dcloud.net.cn/uniapp/images/banana.jpg',
    favorite_count: 96,
    download_count: 384,
    is_favorite: true
  }
];

onLoad((options) => {
  loadSearchHistory();
  if (options?.keyword) {
    searchKeyword.value = options.keyword;
    autoFocus.value = false;
    handleSearch();
  }
});

// 加载搜索历史
const loadSearchHistory = () => {
  const history = uni.getStorageSync('search_history') || [];
  searchHistory.value = history;
};

// 保存搜索历史
const saveSearchHistory = (keyword) => {
  if (!keyword.trim()) return;
  
  let history = uni.getStorageSync('search_history') || [];
  // 去重并放在最前面
  history = history.filter(item => item !== keyword);
  history.unshift(keyword);
  // 最多保存10条
  if (history.length > 10) {
    history = history.slice(0, 10);
  }
  uni.setStorageSync('search_history', history);
  searchHistory.value = history;
};

// 清空搜索历史
const clearHistory = () => {
  uni.showModal({
    title: '提示',
    content: '确定要清空搜索历史吗？',
    success: (res) => {
      if (res.confirm) {
        uni.removeStorageSync('search_history');
        searchHistory.value = [];
      }
    }
  });
};

// 清空搜索框
const clearSearch = () => {
  searchKeyword.value = '';
  showHistory.value = true;
  isSearching.value = false;
  wallpapers.value = [];
};

// 取消搜索
const handleCancel = () => {
  uni.navigateBack();
};

// 处理搜索
const handleSearch = async () => {
  const keyword = searchKeyword.value.trim();
  if (!keyword) return;
  
  showHistory.value = false;
  isSearching.value = true;
  page.value = 1;
  wallpapers.value = [];
  hasMore.value = true;
  
  saveSearchHistory(keyword);
  await searchWallpapers(keyword);
};

// 按历史搜索
const searchByHistory = (keyword) => {
  searchKeyword.value = keyword;
  handleSearch();
};

// 按关键词搜索
const searchByKeyword = (keyword) => {
  searchKeyword.value = keyword;
  handleSearch();
};

// 搜索壁纸
const searchWallpapers = async (keyword) => {
  try {
    uni.showLoading({ title: '搜索中' });
    
    // 调用wallpaper/search云函数
    try {
      const res = await uniCloud.callFunction({
        name: 'wallpapersearch',
        data: {
          keyword: keyword,
          page: page.value,
          size: size.value
        }
      });
        console.log('搜索jieguo:', res);
      if (res && res.result && res.result.code === 0) {
        // 成功获取云函数数据
        if (page.value === 1) {
          wallpapers.value = res.result.data.list || [];
          totalCount.value = res.result.totalCount || 0;
        } else {
          wallpapers.value = [...wallpapers.value, ...(res.result.data.list || [])];
        }
        hasMore.value = res.result.data.hasMore || false;
        loadStatus.value = 'more';
      } else {
        console.error('搜索失败:', res.result);
        loadStatus.value = 'error';
        // 使用模拟数据
        console.log('使用模拟搜索数据');
        await useMockSearchData();
      }
    } catch (cloudError) {
      console.error('搜索失败:', cloudError);
      // 使用模拟数据
      console.log('云函数调用失败，使用模拟搜索数据');
      await useMockSearchData();
    }
  } finally {
    uni.hideLoading();
  }
};

// 使用模拟搜索数据
const useMockSearchData = async () => {
  await new Promise(resolve => setTimeout(resolve, 800));
  
  if (page.value === 1) {
    wallpapers.value = mockSearchResults;
    totalCount.value = mockSearchResults.length + Math.floor(Math.random() * 20);
  } else {
    wallpapers.value = [...wallpapers.value, ...mockSearchResults.map((item, index) => ({
      ...item,
      _id: `${item._id}-page${page.value}-${index}`
    }))];
  }
  
  if (page.value >= 2) {
    hasMore.value = false;
  }
};

// 加载更多
const loadMoreWallpapers = async () => {
  if (!hasMore.value || loadStatus.value === 'loading') return;
  
  loadStatus.value = 'loading';
  page.value++;
  await searchWallpapers(searchKeyword.value.trim());
};

// 导航到详情
const navigateToDetail = (wallpaper) => {
  uni.navigateTo({ url: `/pages/detail/detail?id=${wallpaper._id}` });
};

// 处理收藏
const handleFavorite = async (updatedWallpaper) => {
  try {
    // 更新搜索结果中的收藏状态
    const index = wallpapers.value.findIndex(item => item._id === updatedWallpaper._id);
    if (index !== -1) {
      wallpapers.value[index].is_favorite = updatedWallpaper.is_favorite;
      wallpapers.value[index].favorite_count = updatedWallpaper.favorite_count;
    }
  } catch (error) {
    console.error('更新收藏状态失败:', error);
  }
};
</script>

<style scoped lang="less">
.icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
.search-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  
  .search-header {
    display: flex;
    align-items: center;
    padding: 10px 16px;
    background-color: #fff;
    border-bottom: 1px solid #f0f0f0;
    position: sticky;
    top: 0;
    z-index: 100;
    
    .search-input-wrapper {
      flex: 1;
      display: flex;
      align-items: center;
      background-color: #f0f0f0;
      border-radius: 20px;
      padding: 8px 16px;
      margin-right: 12px;
      
      .search-input {
        flex: 1;
        margin: 0 8px;
        font-size: 16px;
        color: #333;
      }
      
      .search-input::-webkit-input-placeholder {
        color: #999;
      }
    }
    
    .cancel-btn {
      font-size: 16px;
      color: #007aff;
      padding: 0 4px;
    }
  }
  
  .search-history {
    background-color: #fff;
    padding: 16px;
    
    .history-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;
      
      .history-title {
        font-size: 14px;
        color: #999;
      }
    }
    
    .history-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      margin-bottom: 24px;
      
      .history-tag {
        padding: 6px 16px;
        background-color: #f5f5f5;
        border-radius: 16px;
        font-size: 14px;
        color: #333;
        
        &:active {
          background-color: #e5e5e5;
        }
      }
    }
    
    .hot-search {
      .hot-title {
        font-size: 14px;
        color: #999;
        display: block;
        margin-bottom: 12px;
      }
      
      .hot-tags {
        display: flex;
        flex-direction: column;
        gap: 12px;
        
        .hot-tag {
          display: flex;
          align-items: center;
          font-size: 16px;
          color: #333;
          
          &.top-three {
            color: #f5222d;
          }
          
          .hot-rank {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 20px;
            height: 20px;
            background-color: #f5222d;
            color: #fff;
            font-size: 12px;
            border-radius: 4px;
            margin-right: 12px;
          }
          
          .hot-keyword {
            flex: 1;
          }
        }
      }
    }
  }
  
  .search-result {
    .result-header {
      padding: 12px 16px;
      font-size: 14px;
      color: #666;
      background-color: #fff;
      border-bottom: 1px solid #f0f0f0;
    }
    
    .no-result {
      padding: 60px 20px;
      display: flex;
      flex-direction: column;
      align-items: center;
      background-color: #fff;
      
      .no-result-text {
        margin-top: 16px;
        font-size: 16px;
        color: #333;
      }
      
      .no-result-hint {
        margin-top: 8px;
        font-size: 14px;
        color: #999;
      }
    }
  }
}
</style>